package com.yaoxun.console.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.yaoxun.console.constant.GlobalConstant;
import com.yaoxun.console.context.SubjectContextHolder;
import com.yaoxun.console.service.LoginService;
import com.yaoxun.console.xo.dto.LoginSession;

public class SecurityInterceptor implements AsyncHandlerInterceptor {

	private String loginPage = "/login.html";
	
	@Autowired
	private LoginService loginService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		LoginSession session = loginService.getSession(request);
		
		if(session == null) {
			response.addHeader(GlobalConstant.NO_AUTH_HEADER_NAME, "true");
			response.sendRedirect(loginPage);
			return false;			
		}
		
		loginService.refreshSession(response, session);
		
		SubjectContextHolder.setContext(session);
		
		return true;
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		SubjectContextHolder.clearContext();
	}

	
	
	
}
